<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>学员学习情况管理</span>
      </div>
    </template>

    <!-- 搜索表单 -->
    <el-form inline>

      <el-form-item label="培训计划">
        <el-select v-model="user.trainingPlanId" placeholder="请选择培训计划" style="width: 200px">
          <el-option v-for="item in trainingPlanList" :key="item.value" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="姓名">
        <el-input v-model="user.name" placeholder="请输入姓名" style="width: 200px"></el-input>
      </el-form-item>
      <el-form-item label="所属机构">
        <el-select v-model="user.agencyId" placeholder="请选择所属机构" style="width: 340px">
          <el-option v-for="item in agencyList" :key="item.value" :label="item.name" :value="item.id" />
        </el-select>
        <el-button type="primary" @click="show" style="margin-left: 15px;">查询</el-button>
        <el-button @click="clear">重置</el-button>
        <el-button type="primary" @click="exportData">导出</el-button>
      </el-form-item>


    </el-form>

    <el-form>
      <el-row>
        <el-col :span="10">
          <el-form-item label="总体学习完成度">{{ rateOfLearning }}</el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="完成/总人数">{{ completedNum }}/{{ uncompletedNum }}</el-form-item>
        </el-col>
      </el-row>
    </el-form>





    <el-table ref="multipleTable" :data="tableData" style=" width: 100%;">
      <el-table-column prop="id" label="编号" header-align="center" align="center" width="80"></el-table-column>
      <el-table-column prop="name" label="姓名" header-align="center" align="center"></el-table-column>
      <el-table-column prop="agencyId" label="归属机构" header-align="center" align="center">
        <template slot-scope="scope">
          {{ getAgencyName(scope.row.agencyId) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="80" header-align="center" align="center">
        <template slot-scope="scope">
          <el-button class="el-icon-reading" type="primary" circle plain @click="updateInfo(scope.row.id)">
          </el-button>

        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>


    <el-dialog title="学习情况" :visible.sync="dialogVisible" :before-close="close">

      <el-table highlight-current-row ref="multipleTable" :data="userSituation" style=" width: 100%;">
        <el-table-column prop="documentVideoId" label="视频文档编号"></el-table-column>
        <el-table-column prop="type" label="文档视频名">
          <template slot-scope="scope">
            {{ getDocumentVideoName(scope.row.documentVideoId) }}
          </template>
        </el-table-column>
        <el-table-column prop="percentage" label="完成进度">
          <template slot-scope="scope">
            {{ scope.row.percentage }}%
          </template>
        </el-table-column>

      </el-table>
    </el-dialog>

  </el-card>


</template>
<script>


import { addUser, changeUser, deleteUser, getAllUsers } from "@/api/user";
import { getAgencyList } from "@/api/agency";
import { getTrainingPlanList } from "@/api/trainingPlan";
import { getLearningSituationList, getLearningSituationOfOnePlan } from "@/api/learningSituation";
import { getDocumentVideoList } from "@/api/documentVideo";
import FileSaver from "file-saver";
import * as XLSX from "xlsx";

export default {
  data() {
    return {
      background: true,
      // 每页显示的条数
      pageSize: 5,
      // 总记录数
      totalCount: 100,
      // 当前页码
      currentPage: 1,
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      // 表格数据
      tableData: [],
      addOrUpdate: true,//true为add
      user: {},
      form: {},
      posts: [],
      multipleSelection: [],
      selectedIds: [],
      agencyList: [],
      formLabelWidth: "80px",
      theMajorOfMy: "",
      trainingPlanList: [],
      userSituation: [],
      documentVideoList: [],
      loading: false,
      //统计分析
      rateOfLearning: 0,
      completedNum: 0,
      uncompletedNum: 0,


    }
  },
  methods: {

    show() {
      this.rateOfLearning = 0;
      this.completedNum = 0;
      this.uncompletedNum = 0;
      getLearningSituationOfOnePlan(this.user, this.currentPage, this.pageSize).then((res) => {
        console.log(res)
        if (res.data.code === 1) {
          this.totalCount = res.data.data.total;
          this.tableData = res.data.data.rows;
          if (this.tableData.length === 0 && this.currentPage > 1) {
            this.currentPage -= 1;
            this.show()
          }

          //计算统计属性
          let totalAverage = 0;
          this.uncompletedNum = this.tableData.length;

          for (let i = 0; i < this.tableData.length; i++) {

            let totalPercentage = 0; // 用于累加所有percentage值
            let num = 0;
            for (let j = 0; j < this.tableData[i].learningSituation.length; j++) {

              // 累加percentage值
              totalPercentage += this.tableData[i].learningSituation[j].percentage;
              if (this.tableData[i].learningSituation[j].percentage === 100) {
                num += 1;
              }
              if (num === this.tableData[i].learningSituation.length) {
                this.completedNum += 1;
              }
            }
            if (this.tableData[i].learningSituation.length !== 0) {
              let averagePercentage = totalPercentage / this.tableData[i].learningSituation.length;
              totalAverage += averagePercentage;
              //console.log("averagePercentage", averagePercentage)
            }
          }
          this.rateOfLearning = totalAverage / this.tableData.length;


        } else {
          this.$message.error(res.data.msg);
        }
      }).catch((e) => {
      })
    },
    clear() {
      this.user = {};
      this.tableData = [];


      this.rateOfLearning = 0;
      this.completedNum = 0;
      this.uncompletedNum = 0;

    },
    add() {
      this.user = {};
      this.user.password = "1234567";
      this.addOrUpdate = true;
      this.dialogVisible = true;
    },
    addForm() {

      if (this.addOrUpdate) {
        addUser(this.user).then(res => {
          if (res.data.code === 1) {
            this.$message.success("保存成功")
            this.dialogVisible = false;
            this.show();
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(e => {
        });
      } else {
        changeUser(this.user).then(res => {
          console.log(res)
          if (res.data.code === 1) {
            this.$message.success("更新成功")
            this.dialogVisible = false;
            this.user.status = "正常";
            this.show();
          }
        }).catch(e => {
        });
      }

    },

    close() {
      this.dialogVisible = false;
      this.user = {}
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    updateInfo(id) {
      this.addOrUpdate = false;
      this.userSituation = this.tableData.filter(data => data.id == id)[0].learningSituation;
      this.dialogVisible = true;
    },

    getAllAgencyList() {
      getAgencyList().then((res) => {
        if (res.data.code === 1) {
          this.agencyList = res.data.data;
        }
      }).catch((e) => {
      })
    },
    getAgencyName(id) {
      let agency = this.agencyList.find(data => data.id === id);
      return agency ? agency.name : "";
    },
    //分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val;
      this.show();
    },
    handleCurrentChange(val) {
      // 重新设置当前页码
      this.currentPage = val;
      this.show();
    },

    getTrainingsPlanList() {
      getTrainingPlanList().then((res) => {
        if (res.data.code === 1) {
          this.trainingPlanList = res.data.data;
        } else {
          console.log(res.data.msg);
        }
      }).catch((e) => {
      })
    },

    getDocumentVideoName(id) {
      const types = this.documentVideoList.find(t => t.id === id);
      return types ? types.name : '';
    },
    getDocumentVideoLists() {
      getDocumentVideoList().then((res) => {
        if (res.data.code === 1) {
          this.documentVideoList = res.data.data;
        }
      }).catch((e) => {
      })
    },
    getTrainingPlanName(id) {
      const types = this.trainingPlanList.find(t => t.id === id);
      return types ? types.name : '';
    },

    //导出
    async exportData() {

      this.loading = true;
      this.currentPage = 1;
      this.pageSize = this.totalCount;


      try {
        await getLearningSituationList(this.user).then((res) => {
          if (res.data.code === 1) {
            this.tableData = res.data.data;
            //将learningSituationList拆开放入属性中
            let dataList = [];
            for (let i = 0; i < this.tableData.length; i++) {
              let t = {
                id: this.tableData[i].id,
                name: this.tableData[i].name,
                agencyId: this.tableData[i].agencyId
              }
              if (this.tableData[i].learningSituation !== null) {
                for (let j = 0; j < this.tableData[i].learningSituation.length; j++) {
                  let situation = this.tableData[i].learningSituation[j];
                  // 将 learningSituation 的属性添加到 rowData 中，通过添加前缀来避免属性名冲突
                  t[`documentVideoId_${situation.documentVideoId}_percentage`] = situation.percentage + '%'; // 例如：percentage_0, name_0 等
                }
              }
              dataList.push(t);
            }
            const data = dataList;

            // 创建工作簿对象
            const wb = XLSX.utils.book_new();

            // 将数据添加到工作簿中，假设 data 是一个二维数组或对象数组
            // 如果 data 是对象数组，使用 XLSX.utils.json_to_sheet(data)
            // 如果 data 是二维数组，使用 XLSX.utils.aoa_to_sheet(data)
            const ws = XLSX.utils.json_to_sheet(data);

            // 将工作表添加到工作簿中
            XLSX.utils.book_append_sheet(wb, ws, "Sheet1");
            // 写入工作簿，生成 XLSX 文件
            const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
            // 使用 FileSaver 保存文件
            try {
              FileSaver.saveAs(
                new Blob([wbout], { type: "application/octet-stream" }),
                this.getTrainingPlanName(this.user.trainingPlanId) + "_学习进度.xlsx"
              );
            } catch (e) {
              console.error(e);
            }


          }
        }).catch((e) => { })
      } finally {
        this.currentPage = 1;
        this.pageSize = 5;
        this.show();
        this.loading = false;
      }
    },


  },
  mounted() {
    this.getAllAgencyList();
    this.getTrainingsPlanList();
    this.getDocumentVideoLists();
  },
};
</script>


<style>
* {
  margin: 0;
  padding: 0;
}
</style>
